package com.sofwin;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * @packageName: com.sofwin
 * @user: andyliu
 * @date: 2021/7/9 11:25
 * @email 115176513@qq.com
 * @description: TODO
 */
@Configuration
@MapperScan(basePackages = {"com.sofwin.mapper","com.sofwin.system.mapper"})
@EnableTransactionManagement
public class MybatisConfiter {
    @Bean
    public DataSource getDataSource(){
        DruidDataSource ds  = new DruidDataSource();
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost/db1");
        ds.setUsername("root");
        ds.setPassword("123456");
        return ds;
    }
    @Bean(name="factory")
    public SqlSessionFactoryBean getSqlSessionFactory(){
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(getDataSource());
        bean.setTypeAliasesPackage("com.sofwin.pojo,com.sofwin.system.pojo,com.sofwin.system.vo,com.sofwin.system.dto");
        PageInterceptor interceptor =new PageInterceptor();
        Properties pro = new Properties();
        pro.setProperty("helperDialect","mysql");
        Resource path = new ClassPathResource("mybatis-config.xml");
        bean.setConfigLocation(path);
        interceptor.setProperties(pro);
        bean.setPlugins(interceptor);
        return bean;
    }
//    @Bean
//    public MapperScannerConfigurer getMapperConfiger(){
//        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
//        configurer.setSqlSessionFactoryBeanName("factory");
//        configurer.setBasePackage("com.sofwin.mapper");
//        return configurer;
//    }
    @Bean
    public PlatformTransactionManager getTransactionManager(){
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        manager.setDataSource(getDataSource());
        return manager;
    }
}
